const PRIVACYNAME = '《嗨猫互动小程序隐私保护指引》';

Component({
  properties: {
    needAutoShow: { // 是否需要弹窗自动弹出(条件满足的时候)
      value: false,
      type: Boolean
    }
  },
  data: {
    privacyAuthorizeVisible: false,
    privacyContractName: '',
  },
  lifetimes: {
    async attached() {
      try {
        this.watchNeedPrivacyAuthEvent();
        const needAuthorization = await this.getPrivacyAuthInfo();
        this.autoShowLogic(needAuthorization);
      } catch (err) {
        console.log(err);
      }
    },
    detached() {}
  },
  methods: {
    // 打开隐私协议具体内容
    onPrivacyContractOpen() {
      wx.openPrivacyContract({
        success: () => {}, // 打开成功
        fail: () => {}, // 打开失败
        complete: () => {}
      });
    },
    // 同意授权
    onAgree() {
      this.privacyAuthResolve({
        event: 'agree',
        buttonId: 'agree-btn'
      });
      this.setData({
        privacyAuthorizeVisible: false
      });
    },
    // 拒绝授权
    onDisagree() {
      this.privacyAuthResolve({
        event: 'disagree'
      });
      this.setData({
        privacyAuthorizeVisible: false
      });
    },
    // 监听“需要隐私授权”事件
    watchNeedPrivacyAuthEvent() {
      wx.onNeedPrivacyAuthorization((resolve) => {
        // 打开隐私授权弹窗
        this.setData({
          privacyAuthorizeVisible: true
        });
        // 暂存resolve(授权上报函数)
        this.privacyAuthResolve = resolve;
      });
    },
    // 查询隐私名称、是否需要隐私授权
    getPrivacyAuthInfo() {
      return new Promise((resolve, reject) => {
        wx.getPrivacySetting({
          success: (res) => {
            console.log("是否需要授权：", res.needAuthorization, "隐私协议的名称为：", res.privacyContractName);
            if (res.needAuthorization) {
              this.setData({
                privacyContractName: res.privacyContractName || PRIVACYNAME
              });
              resolve(res.needAuthorization);
            }
          },
          fail: (err) => {
            console.log(err);
            reject(err);
          },
        })
      })
    },
    // 自动弹出隐私授权窗(条件满足的情况)的逻辑
    // 条件：需要隐私授权并且需要自动弹出
    autoShowLogic(needPrivacyAuth) {
      if (needPrivacyAuth === true && this.data.needAutoShow) {
        wx.requirePrivacyAuthorize({});
      }
    }
  },
});